package com.example.cdpbookstore.web.servlet;

import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.digest.BCrypt;
import com.example.cdpbookstore.pojo.entity.Customer;
import com.example.cdpbookstore.service.CustomerService;
import com.example.cdpbookstore.service.impl.CustomerServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;

@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
    private final CustomerService customerService = new CustomerServiceImpl();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String email = req.getParameter("email");
        String password = req.getParameter("password");
        String captcha = req.getParameter("captcha");


        String usernameErr = null;
        String emailErr = null;
        String captchaErr = null;
        // 用户名查重
        Customer customer1 = customerService.getByUsernameOrEmail(username);
        if (customer1 != null) {
            usernameErr = "用户名重复";
            req.setAttribute("usernameErr", usernameErr);
        }
        // 邮件查重
        Customer customer2 = customerService.getByUsernameOrEmail(email);
        if (customer2 != null) {
            emailErr = "邮箱重复";
            req.setAttribute("emailErr", emailErr);
        }
        // 验证码比对
        String captcha1 = (String) req.getSession().getAttribute("captcha");
        System.out.println("校验的验证码是：" + captcha1);
        if (!captcha.equals(captcha1)) {
            captchaErr = "验证码错误";
            req.setAttribute("captchaErr", captchaErr);
        }

        if (usernameErr != null || emailErr != null || captchaErr != null) {
            req.getRequestDispatcher("register.jsp").forward(req, resp);
            return;
        }


        Customer customer = new Customer();
        customer.setId(IdUtil.randomUUID());
        customer.setUsername(username);
        customer.setPassword(BCrypt.hashpw(password, BCrypt.gensalt()));
        customer.setEmail(email);

        LocalDateTime now = LocalDateTime.now();
        customer.setCreationTime(now);
        customer.setUpdateTime(now);

        if (customerService.save(customer)) {
            // 页面跳转
            req.setAttribute("page", "index.jsp");
            req.setAttribute("message", "注册成功");
            req.getRequestDispatcher("delay_jump.jsp").forward(req, resp);
        } else {
            // 页面跳转
            req.setAttribute("page", "register.jsp");
            req.setAttribute("message", "注册失败");
            req.getRequestDispatcher("delay_jump.jsp").forward(req, resp);
        }
    }
}
